<?php

// 仅当会话尚未启动时调用 session_start()
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}


// 检查用户是否为读者角色
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'reader') {
    header('Location: http://localhost/Library_management_system/index.php');
    exit();
}

// 数据库连接配置
$host = 'localhost';  // 数据库主机
$dbname = 'library';  // 数据库名称
$dbusername = 'root';  // 数据库用户名
$dbpassword = '123456';  // 数据库密码

// 创建数据库连接
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $dbusername, $dbpassword);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("连接失败: " . $e->getMessage());
}

// 获取当前用户ID
$user_id = $_SESSION['u_No']; // 确保用户登录后设置了 session

// 初始化错误信息
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $book_id = $_POST['book_id'];  // 获取图书ID

    // 1. 检查用户是否被冻结
    $stmt = $pdo->prepare("SELECT state FROM users WHERE u_No = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user['state'] == '冻结') {
        $error_message = '您的账户已被冻结，无法借阅图书！';
    } else {
        // 2. 检查图书是否可借（不需要更新库存）
        $stmt = $pdo->prepare('SELECT Loan_Id FROM Loan WHERE book_No = ? AND state_ID IN ("S001", "S003")');
        $stmt->execute([$book_id]);
        $book = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$book) {  // 如果没有正在借阅的记录
            // 3. 创建新的借阅记录
            $loan_id = uniqid();  // 使用唯一ID创建借阅记录
            $borrow_date = date('Y-m-d H:i:s');  // 当前日期作为借阅日期
            $stmt = $pdo->prepare('INSERT INTO Loan (Loan_Id, state_ID, book_No, u_No, loan_date, Return_date) 
                                   VALUES (?, "S001", ?, ?, ?, NULL)');
            $stmt->execute([$loan_id, $book_id, $user_id, $borrow_date]);

            // 4. 更新 book 表中的 Loan_Id 字段，关联到当前借阅记录
            $stmt = $pdo->prepare('UPDATE book SET Loan_Id = ? WHERE book_No = ?');
            $stmt->execute([$loan_id, $book_id]);

            

            // 5. 增加图书推荐度
            $stmt = $pdo->prepare('SELECT Recommendation_degree FROM book WHERE book_No = ?');
            $stmt->execute([$book_id]);
            $book = $stmt->fetch(PDO::FETCH_ASSOC);

            $new_recommendation_degree = $book['Recommendation_degree'] + 10;
            $stmt = $pdo->prepare('UPDATE book SET Recommendation_degree = ? WHERE book_No = ?');
            $stmt->execute([$new_recommendation_degree, $book_id]);

            echo "借书成功！该图书的推荐度已增加 10。";
            exit();
        } else {
            $error_message = "该图书当前不可借阅，可能已经借出或正在归还。";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>借书</title>
</head>
<body>
    <h2>借书</h2>

    <?php if ($error_message): ?>
        <div style="color: red;">
            <p><?php echo $error_message; ?></p>
        </div>
    <?php endif; ?>

    <form method="POST">
        <label for="book_id">选择图书ID:</label>
        <input type="text" name="book_id" required>
        <button type="submit">借书</button>
    </form>
</body>
</html>
